
import sys
import serial
import time
from threading import Thread

PORTNAME = 'COM1'

if len(sys.argv) < 2:
	print 'you can select port with first argument eg: COM3'
else:
	PORTNAME = sys.argv[1]
	print 'chosen port: %s' % (PORTNAME, )


class Packet:
	""" defines format of data received from device
	"""
	
	LENGTH = 9
	STARTER = '@'
	
	def __init__(self, x=0, y=0):
		self.x = x
		self.y = y

	def load(self, chunk):
		""" loads from chunk, eats up chunk.
		"""
		while len(chunk) >= self.LENGTH:
			if chunk[0] == self.STARTER:
				self.x = self.packit(chunk[1], chunk[2])
				self.y = self.packit(chunk[3], chunk[4])
				self.r1 = self.packit(chunk[5], chunk[6])
				self.r2 = self.packit(chunk[7], chunk[8])
				for x in range(self.LENGTH): chunk.pop(0)
				return True
			else:
				chunk.pop(0)
		return False

	def packit(self, hi, lo):
		ret = ((int(hi))<<8) | (int(lo))
		if hi & 0x80: ret |= 0xFFFF0000
		return ret

class PortISR(Thread):
	""" handles onreceive port event ..
	"""
	def __init__(self, port):
		Thread.__init__(self)
		self._port = port
		self._packet = Packet()
		self.chunk = []
	
	def run(self):
		while 1:
			self.chunk += list(self._port.read())
			if self._packet.load( self.chunk ):
				## display new results
				print '%s: %s, %s' % (time.ctime(), self._packet.x, self._packet.y, )

def main():
	print 'open %s' % (PORTNAME, )
	port = serial.Serial(PORTNAME)
	port.open()

	handler = PortISR(port)
	handler.start()
	
	while 1:
		#do something else ..
		pass


if __name__ == '__main__':
	main()
